package com.example.controller;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.example.domain.po.User;
import com.example.service.UserService;
import com.example.util.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wxLogin")
public class WeChatController {

    @Autowired
    private UserService userService;
    private static final String APPID = "wx38832ce9cb253734";
    private static final String APPSECRET = "4358b0adb8537fda56d6b08cd33dde95";

    @PostMapping("/getUserInfo")
    public Map<String,Object> insert(@RequestParam("code") String code, HttpSession session) throws ClientProtocolException, IOException {
        //返回map
        System.err.println("微信授权登录");
        System.err.println("code值： "+code);
        Map<String,Object> resultMap = new HashMap<>();
        String appid = APPID; //APPID
        String secret = APPSECRET; //SECRET

        // URL 编码
        String encodedCode = URLEncoder.encode(code, "UTF-8");
        // 构造请求 URL
//        String loginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid
//                + "&secret=" + secret
//                + "&js_code=" + encodedCode
//                + "&grant_type=authorization_code";

        String loginUrl="https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+secret+"&js_code="+code+"&grant_type=authorization_code";
        try {
            CloseableHttpClient client = null;
            CloseableHttpResponse response = null;
            try {
                // 创建http GET请求
                HttpGet httpGet = new HttpGet(loginUrl);
                client = HttpClients.createDefault();
                // 执行请求
                response = client.execute(httpGet);
                HttpEntity entity = response.getEntity();//得到返回数据
                String result = EntityUtils.toString(entity);
                System.err.println("微信返回的结果"+result);
                resultMap.put("data", result);//进行封装
                System.err.println(resultMap);
                JSONObject json_test = JSONObject.parseObject(result);
                String wxOpenid = json_test.getString("openid");
                String sessionKey = json_test.getString("session_key");
                System.err.println("openid值: "+wxOpenid);//得到微信openID
                System.err.println("sessionKey值: "+sessionKey);

                resultMap.put("state", 1);
                resultMap.put("data", wxOpenid);
                resultMap.put("sessionKey", sessionKey);

                if(StringUtils.isEmpty(wxOpenid)){
                    resultMap.put("state", 0);
                    resultMap.put("message", "未获取到openid");
                    return resultMap;
                }
            } finally {
                if (response != null) {
                    response.close();
                }
                if (client != null) {
                    client.close();
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resultMap;
    }

    @PostMapping("/getphone")
    public Result<User> mini_getPhone(HttpServletRequest request, @RequestBody Map<String,String> map)
    {
        System.out.println(map);
        String sessionKey = map.get("sessionKey");
        String encryptedData = map.get("encryptedData");
        String iv = map.get("iv");

        //
        System.out.println("encryptedData= "+encryptedData);
        System.out.println("iv= "+iv);
        System.out.println("sessionKey= "+sessionKey);
        JSONObject obj=getPhoneNumber(sessionKey,encryptedData,iv);//解密电话号码
        //System.out.println(obj);
        //获取手机号
        String phone=obj.get("phoneNumber").toString();
        System.err.println("sphone= "+phone);
        //通过手机号到数据库查询用户是否注册
        User user = userService.findByPhone(phone);
        if(user==null){
            //为空，为其注册信息
            userService.register(phone);
        }else{
            return Result.success(user);
        }
        //返回用户信息
        return Result.success(userService.findByPhone(phone));
    }

    //解析电话号码
    public JSONObject getPhoneNumber(String session_key, String encryptedData, String iv) {
        byte[] dataByte = Base64.decode(encryptedData);
        byte[] keyByte = Base64.decode(session_key);
        byte[] ivByte = Base64.decode(iv);
        try {

            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}